package rmmk.framework.datasources.abstracts;

import java.util.Collections;
import java.util.List;
import java.util.Vector;

import rmmk.framework.Utils;
import rmmk.framework.datasources.Document;

/**
 * Klasa oferująca wielowątkową pracę na dokumentach
 * @author marcin
 *
 */
public abstract class AbstractDocumentWorker implements Runnable {

	int cores, shift;
	private List<Document> documents;

	private AbstractDocumentWorker(int cores, int shift, List<Document> documents) {
		this.shift = shift;
		this.cores = cores;
		this.documents = documents;
	}

	public void process(List<Document> documents) {
		int cores = Utils.getProcessorsCount();

		Vector<Thread> threads = new Vector<>();

		for (int i = 0; i < cores; ++i) {
			threads.add(new Thread(getImpl(cores, i, 
					Collections.synchronizedList(documents))));
		}

		for (Thread t : threads)
			try {
				t.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}

	protected abstract void process(Document document, List<Document> listOfAllDocuments);

	protected abstract AbstractDocumentWorker getImpl(int cores, int shift, List<Document> documents);

	@Override
	public void run() {
		for(int i = shift; i < documents.size(); i+=shift)
			process(documents.get(i), this.documents);
	}

}
